package pl.game;

import android.graphics.Canvas;
import android.view.SurfaceHolder;

public class MainThread extends Thread{
	
	static final long FPS = 1000;
	
	private SurfaceHolder surfaceHolder;
	private MapView mapView;
	private boolean running;
	
	public void setRunning(boolean running) {
		this.running = running;
	}

	public MainThread(SurfaceHolder surfaceHolder, MapView mapView) {
		super();
		this.surfaceHolder = surfaceHolder;
		this.mapView = mapView;
	}

	@Override
	public void run() {
        long ticksPS = 1000 / FPS;
        long startTime;
        long sleepTime;
		Canvas canvas;
		while (running) {
			canvas = null;
			startTime = System.currentTimeMillis();
			try {
				canvas = this.surfaceHolder.lockCanvas();
				synchronized (surfaceHolder) {
					this.mapView.onDraw(canvas);				
				}
			} finally {
				if (canvas != null) {
					surfaceHolder.unlockCanvasAndPost(canvas);
				}
			}
			sleepTime = ticksPS - (System.currentTimeMillis() - startTime);
            try {
                   if (sleepTime > 0)
                          sleep(sleepTime);
                   else
                          sleep(10);
            } catch (Exception e) {}
		}
	}
	
}